package com.jfee.dds.rest;

import com.jfee.dds.constants.CommonConstants;
import com.jfee.dds.datasource.DynamicDataSource;
import com.jfee.dds.enums.ResultStatusCode;
import com.jfee.dds.mapper.DbMapper;
import com.jfee.dds.model.Db;
import com.jfee.dds.utils.ProcessDataUtils;
import com.jfee.dds.vo.Result;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 数据库动态初始
 *
 * @author sf.xiong
 * @version 2019-05-31
 */
@RestController
@RequestMapping(value = "/api/db")
public class DBController extends BaseController {

    @Autowired
    private DbMapper dbMapper;

    @Autowired
    private ProcessDataUtils processDataUtils;

    @Autowired
    private HashOperations<String, String, Object> hashOperations;

    @Autowired
    private DynamicDataSource dynamicDataSource;

    @PostMapping(value = "/v1/create")
    public Result createDb(Db db) {
        Result result = new Result();
        try {
            //数据库表结构初始
            dbMapper.create(db);
            processDataUtils.writeFile(db.getDbName());
            ScriptRunner runner = new ScriptRunner(dynamicDataSource.getConnection());
            Resources.setCharset(Charset.forName("utf-8"));
            runner.runScript(Resources.getResourceAsReader("init-db-run.sql"));
            runner.closeConnection();
            //更新Redis缓存
            Map<String, Object> tenantInfoMap = hashOperations.entries(CommonConstants.RDS_TENANT_INFO_KEY);
            if (!tenantInfoMap.isEmpty()) {
                String tenantId = "db_" + db.getCode();
                if (tenantInfoMap.containsKey(tenantId)) {//存在
                    result.setCodeAndMsg(ResultStatusCode.TENANT_EXITS_ERR);
                    return result;
                }
                tenantInfoMap.put(tenantId, db);
                hashOperations.putAll(CommonConstants.RDS_TENANT_INFO_KEY, tenantInfoMap);
            }
        } catch (IOException e) {
            result.setErr();
        }
        return result;
    }
}
